package com.jzo2o.customer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.dto.WorkerCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {




    /**
     * 根据服务人员id更新
     *
     * @param workerCertificationUpdateDTO 服务人员认证更新模型
     */
    @Override
    public void updateById(WorkerCertificationUpdateDTO workerCertificationUpdateDTO) {
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                .eq(WorkerCertification::getId, workerCertificationUpdateDTO.getId())
                .set(WorkerCertification::getCertificationStatus, workerCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getName()), WorkerCertification::getName, workerCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getIdCardNo()), WorkerCertification::getIdCardNo, workerCertificationUpdateDTO.getIdCardNo())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getFrontImg()), WorkerCertification::getFrontImg, workerCertificationUpdateDTO.getFrontImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getBackImg()), WorkerCertification::getBackImg, workerCertificationUpdateDTO.getBackImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationMaterial()), WorkerCertification::getCertificationMaterial, workerCertificationUpdateDTO.getCertificationMaterial())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationTime()), WorkerCertification::getCertificationTime, workerCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    @Autowired
    private IServeProviderService serveProviderService;

    /**
     * 服务端认证申请
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void certificationApplication(WorkerCertificationAuditAddReqDTO dto) {
        //这里的id存储id是服务提供者的id
        WorkerCertification workerCertification = BeanUtils.copyBean(dto, WorkerCertification.class);
        workerCertification.setServeProviderId(UserContext.currentUserId());
        workerCertification.setId(UserContext.currentUserId());
        workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        workerCertification.setCertificationTime(LocalDateTime.now());
        boolean result = this.save(workerCertification);
        if (!result){
            throw new DBException("保存认证申请失败");
        }
        //成功之后，将服务提供者的状态更改掉
        boolean result1 = serveProviderService.lambdaUpdate()
                .eq(ServeProvider::getId, dto.getServeProviderId())
                .set(ServeProvider::getSettingsStatus,
                        CertificationStatusEnum.PROGRESSING.getStatus())
                .update();
    }

 @Autowired
 private WorkerCertificationMapper workerCertificationMapper;

    @Override
    public RejectReasonResDTO getJectReason() {
        //判断当前用户是否有驳回原因
        //获取当前用户
        Long id = UserContext.currentUserId();
        WorkerCertification workerCertification = this.lambdaQuery().eq(WorkerCertification::getId, id).one();
        if (workerCertification == null){
            return null;
        }
        //如果不为空，就将原因返回
        String rejectReason = workerCertification.getRejectReason();
        RejectReasonResDTO reasonResDTO = RejectReasonResDTO.builder()
                .rejectReason(rejectReason)
                .build();
        return reasonResDTO;
    }


    /**
     * 审核服务人员认证分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult<WorkerCertificationAuditResDTO> getPage(WorkerCertificationAuditPageQueryReqDTO dto) {
        Page<WorkerCertification> pageQuery = PageUtils.parsePageQuery(dto, WorkerCertification.class);
        Page<WorkerCertification> page = this.lambdaQuery()
                .eq(dto.getAuditStatus() != null, WorkerCertification::getAuditStatus, dto.getAuditStatus())
                .eq(dto.getCertificationStatus() != null, WorkerCertification::getCertificationStatus,
                        dto.getCertificationStatus())
                .eq(StringUtils.isNoneBlank(dto.getIdCardNo()), WorkerCertification::getIdCardNo, dto.getIdCardNo())
                .like(dto.getName() != null, WorkerCertification::getName, dto.getName())
                .orderBy(!dto.getIsAsc1(), dto.getIsAsc1(), WorkerCertification::getCreateTime)
                .page(pageQuery);
        PageResult<WorkerCertificationAuditResDTO> pageResult = PageUtils.toPage(page, WorkerCertificationAuditResDTO.class);
        return pageResult;
    }


    /**
     * 服务人员认证信息
     * @param id
     * @param certificationStatus
     * @param rejectReason
     */
    @Override
    public void auditWorkerInfo(Long id, Long certificationStatus, String rejectReason) {
        //判断当前用户是否存在
        WorkerCertification workerCertification = this.lambdaQuery().eq(WorkerCertification::getId, id)
                .one();
        if (workerCertification == null){
            throw new ForbiddenOperationException("不存在");
        }
        //获取当前用户的名称
        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        String name = currentUserInfo.getName();
        //更改当前用户的状态
        boolean result = this.lambdaUpdate().eq(WorkerCertification::getId, id)
                .set(WorkerCertification::getAuditStatus, AuditStatusEnum.AUDITED.getStatus())
                .set(WorkerCertification::getCertificationStatus, certificationStatus)
                .set(WorkerCertification::getAuditorId, UserContext.currentUserId())
                .set(WorkerCertification::getAuditTime, LocalDateTime.now())
                .set(StringUtils.isNotBlank(rejectReason), WorkerCertification::getRejectReason, rejectReason)
                .set(WorkerCertification::getAuditorName, name)
                .update();
        if (!result){
            throw new DBException("数据库异常");
        }

    }
}
